/* Configuration */
//http://212.26.144.107:1456/kadastrova-karta
//var serverMap = 'http://192.168.33.51:80';
var serverMap = 'http://212.26.144.104:5163';
//var serverMap = 'http://212.26.144.107:8092';
//var serverMap = 'http://10.0.6.53';


var untiled;
var tiled;
var pureCoverage = false;


// pink tile avoidance
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
// make OL compute scale according to WMS spec
OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;

//OpenLayers.ProxyHost = "http://212.26.144.107:4156/cgi-bin/proxy.cgi?url=";
OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";

var map, infoo, measureControls, navControls, markers;
//var mapBounds = new OpenLayers.Bounds(21.921242623, 43.5341787107, 42.0119321532, 53.3790101853);
var mapBounds = new OpenLayers.Bounds(18, 44.8, 42, 52);
var mapMinZoom = 2;
var mapMaxZoom = 22

// avoid pink tiles
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
OpenLayers.Util.onImageLoadErrorColor = "transparent";


$(document).ready(function(){
    var map = document.getElementById("map");
    var leftSideWidth = 0;

    map.style.height = (getWindowHeight()-72) + "px";
    map.style.width = (getWindowWidth()-2) + "px";

    init();

    $('#draw_feature_path').click(function(){
        if($(this).hasClass('olControlDrawFeaturePathItemInactive')){
            $(this).removeClass('olControlDrawFeaturePathItemInactive');
            $(this).addClass('olControlDrawFeaturePathItemActive');
            measureControls['line'].activate();
            measureControls['polygon'].deactivate();
            //measureControls['line'].geodesic = true;
            measureControls['line'].setImmediate(true);
            $('#draw_feature_out').html('довжина: 0.000 km');
            $('#draw_feature_out').show();
        }
        else
        {
            $(this).addClass('olControlDrawFeaturePathItemInactive');
            $(this).removeClass('olControlDrawFeaturePathItemActive');
            measureControls['line'].deactivate();
            measureControls['polygon'].deactivate();
            $('#draw_feature_out').hide();
        }

        $('#draw_feature_polygon').removeClass('olControlDrawFeaturePolygonItemActive');
        $('#draw_feature_polygon').addClass('olControlDrawFeaturePolygonItemInactive');

    });

    $('#draw_feature_polygon').click(function(){
        if($(this).hasClass('olControlDrawFeaturePolygonItemInactive')){
            $(this).removeClass('olControlDrawFeaturePolygonItemInactive');
            $(this).addClass('olControlDrawFeaturePolygonItemActive');
            measureControls['polygon'].activate();
            measureControls['line'].deactivate();
            //measureControls['polygon'].polygon = true;
            measureControls['polygon'].setImmediate(true);
            $('#draw_feature_out').html('площа: 0.000 m<sup>2</sup>');
            $('#draw_feature_out').show();

        //navControls.deactivate();
        }
        else
        {
            $(this).addClass('olControlDrawFeaturePolygonItemInactive');
            $(this).removeClass('olControlDrawFeaturePolygonItemActive');
            measureControls['line'].deactivate();
            measureControls['polygon'].deactivate();
            $('#draw_feature_out').hide();
        }

        $('#draw_feature_path').removeClass('olControlDrawFeaturePathItemActive');
        $('#draw_feature_path').addClass('olControlDrawFeaturePathItemInactive');
    });

    $('#map_control_cursor').click(function(){
        $('#draw_feature_path').removeClass('olControlDrawFeaturePathItemActive');
        $('#draw_feature_path').addClass('olControlDrawFeaturePathItemInactive');
        $('#draw_feature_polygon').removeClass('olControlDrawFeaturePolygonItemActive');
        $('#draw_feature_polygon').addClass('olControlDrawFeaturePolygonItemInactive');
        $('#draw_feature_out').hide();

        measureControls['line'].deactivate();
        measureControls['polygon'].deactivate();
    });


    $('#map_control_layers').click(function(){
        if($('#map_container_layers').is(':visible'))
        {
            $('#map_container_layers').hide();
            $('#map_control_layers div:first').removeClass('LayersActive');
            $('#map_control_layers div:first').addClass('LayersInactive');
        }
        else{
            $('#map_container_layers').show();
            $('#map_control_layers div:first').removeClass('LayersInactive');
            $('#map_control_layers div:first').addClass('LayersActive');
        }
    });

    if($('#get_serach_cadnum').val() != '')
    {
        $('.sidebar').hide();
        $('.show-sidebar').show();
        $('#map_toolbar').removeClass('map_toolbar_leftpanel_on');
        $('#map_toolbar').addClass('map_toolbar_leftpanel_off');
        searchCadnum($('#get_serach_cadnum').val());
    }

});

function init(){
    OpenLayers.Lang.setCode("ru");

    var options = {
        controls: [],
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        numZoomLevels: 22,
        maxResolution: 156543.0339,
        maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)
    //maxExtent: new OpenLayers.Bounds(21, 43, 42, 53)
    };


    map = new OpenLayers.Map('map', options);

    map.events.register("moveend", null, function(e) {
        tooltip.close();
    });
    map.events.register("movestart", null, function(e) {
        tooltip.close();
    });

    initLayers();
    initControls();

    if (!map.getCenter()) map.zoomToExtent( mapBounds.transform(map.displayProjection, map.projection ) );

    initPopupInfo();

}// End of INIT

function initLayers()
{
    // if this is just a coverage or a group of them, disable a few items,
    // and default to jpeg format
    format = 'image/png8';
    if(pureCoverage) {
        format = "image/jpeg";
    }


    kadpodil = new OpenLayers.Layer.WMS(
        //"Кадастровий поділ", serverMap+"/rastr/geoserver/wms",
        //"Кадастровий поділ", serverMap+"/vector/geoserver/wms",
        //"Кадастровий поділ", serverMap+"/vector/geoserver/dzk/wms",
        "Кадастровий поділ", serverMap+"/geowebcache/service/wms?tiled=true",
        {
            //LAYERS: 'dzk:new_kadastr',
            LAYERS: 'kadastr',
            STYLES: '',
            format: 'image/png',
            tiled: true,
            transparent: 'true'
        //tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
        },
        {
            buffer: 0,
            displayOutsideMaxExtent: true,
            isBaseLayer: false,
            yx : {
                'EPSG:900913' : false
            }
        //singleTile: true
        // transitionEffect: 'resize'
        }
        );


    mosaic = new OpenLayers.Layer.WMS(
        "dzk:mosaic - Tiled", serverMap+"/rastr/geoserver/gwc/service/wms?tiled=true",
        {
            LAYERS: 'dzk:mosaic',
            STYLES: '',
            format: 'image/jpeg',
            tiled: true,
        //tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
        },
        {
            buffer: 0,
            displayOutsideMaxExtent: true,
            isBaseLayer: true,
            yx : {
                'EPSG:900913' : true
            }
        }
        );

    parcel_auction = new OpenLayers.Layer.WMS(
        "Земельні аукціони", serverMap+"/vector/geoserver/dzk/wms",        
        {
            LAYERS: 'dzk:parcel_auction',
            STYLES: '',
            format: 'image/png',
            tiled: true,
            transparent: 'true'
        //tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
        },
        {
            buffer: 0,
            displayOutsideMaxExtent: true,
            isBaseLayer: false,
            yx : {
                'EPSG:900913' : false
            }
        }
        );



    var gsat = new OpenLayers.Layer.Google(
        "Google - космос",
        {
            type: google.maps.MapTypeId.SATELLITE,
            isBaseLayer: true,
            numZoomLevels: 22
        }
        // used to be {type: G_SATELLITE_MAP, numZoomLevels: 22}
        );


    var gphy = new OpenLayers.Layer.Google(
        "Google - фізична карта",
        {
            type: google.maps.MapTypeId.TERRAIN
        }
        // used to be {type: G_PHYSICAL_MAP}
        );

    var gmap = new OpenLayers.Layer.Google(
        "Google - карта", // the default
        {
            numZoomLevels: 22,
            isBaseLayer: true
        }
        // default type, no change needed here
        );

    var ghyb = new OpenLayers.Layer.Google(
        "Google - космос гібрід",
        {
            type: google.maps.MapTypeId.HYBRID,
            numZoomLevels: 22
        }
        // used to be {type: G_HYBRID_MAP, numZoomLevels: 20}
        );

    var OSM = new OpenLayers.Layer.OSM("Оглядова карта");


    tmsoverlay = new OpenLayers.Layer.TMS( "Карта масштабу М 1:100000", "",
    {   // url: '', serviceVersion: '.', layername: '.',
        type: 'jpg',
        getURL: overlay_getTileURL,
        alpha: true,
        isBaseLayer: true
    });
    if (OpenLayers.Util.alphaHack() == false) {
        tmsoverlay.setOpacity(0.7);
    }

    tmsoverlay_orto = new OpenLayers.Layer.TMS( "Ортофотоплани", "",
    {   // url: '', serviceVersion: '.', layername: '.',
        type: 'jpg',
        getURL: overlay_getTileURL,
        alpha: true,
        isBaseLayer: true
    });
    if (OpenLayers.Util.alphaHack() == false) {
        tmsoverlay_orto.setOpacity(0.7);
    }

    /*tmsoverlay_orto2 = new OpenLayers.Layer.TMS( "Ортофотоплани ДЗА", "",
            {   // url: '', serviceVersion: '.', layername: '.',
                                    type: 'jpg', getURL: overlay_getTileURL, alpha: true,
                                    isBaseLayer: true
            });
    if (OpenLayers.Util.alphaHack() == false) { tmsoverlay_orto2.setOpacity(0.7); }		*/

    /*

            temp_parcel = new OpenLayers.Layer.WMS(
                "участки_временные", serverMap+"/geoserver/dzk/wms",
                {
                    LAYERS: 'dzk:tempdil',
                    STYLES: '',
		transparent: 'true',
                    format: format
                },
                {
                   singleTile: true,
                   ratio: 1,
                   isBaseLayer: false,
                   yx : {'EPSG:900913' : false}
                }
            );
*/

    //map.addLayers([parcel, kadpodil, gmap, gsat, tmsoverlay,]);

    markers = new OpenLayers.Layer.Markers( "Маркери" );

    //map.addLayers([markers, gmap, gsat, gphy, ghyb, tmsoverlay, tmsoverlay_orto, kadpodil]);

//    map.addLayers([markers, OSM, gmap, gsat, gphy, ghyb, tmsoverlay, tmsoverlay_orto, kadpodil, parcel_auction]);
    map.addLayers([markers, OSM, gmap, gsat, gphy, ghyb, tmsoverlay, tmsoverlay_orto, kadpodil]);
    //map.addLayers([OSM, kadpodil]);
/*var report = function(e) {
            OpenLayers.Console.log(e.type, e.feature.id);
        };

        var highlightCtrl = new OpenLayers.Control.SelectFeature(kadpodil, {
            hover: true,
            highlightOnly: true,
            renderIntent: "temporary",
            eventListeners: {
                beforefeaturehighlighted: report,
                featurehighlighted: report,
                featureunhighlighted: report
            }
        });

        var selectCtrl = new OpenLayers.Control.SelectFeature(kadpodil,
            {clickout: true}
        );

        map.addControl(highlightCtrl);
        map.addControl(selectCtrl);

        highlightCtrl.activate();
        selectCtrl.activate();*/
}

function initControls(){
    nav = new OpenLayers.Control.NavigationHistory();
    map.addControl(nav);

    var panel = new OpenLayers.Control.NavToolbar({
        'div':OpenLayers.Util.getElement('map_control_panel')
    });
    var panel_history = new OpenLayers.Control.NavToolbar({
        'div':OpenLayers.Util.getElement('map_control_history')
    });

    panel_history.addControls([nav.previous, nav.next]);

    //map.addControl(panel);
    //map.addControl(panel_history);

    map.addControl(new OpenLayers.Control.Zoom({
        zoomInId: "map_zoom_in",
        zoomOutId: "map_zoom_out"
    }));

    map.addControl(new OpenLayers.Control.DragPan({
        enableKinetic: false
    }));

    navControls = new OpenLayers.Control.Navigation();
    map.addControl(navControls);
    map.addControl(new OpenLayers.Control.Scale(OpenLayers.Util.getElement('scale')));
    //map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));
    map.addControl(new OpenLayers.Control.LayerSwitcher({
        'div':OpenLayers.Util.getElement('map_container_layers')
    }));
    //map.addControl(new OpenLayers.Control.ZoomBox({'div':OpenLayers.Util.getElement('map_zoom_box')}));
    //map.addControl(new OpenLayers.Control.Permalink({anchor: true}));
    map.addControl(new OpenLayers.Control.Permalink({
        'div': OpenLayers.Util.getElement('permalink')
    }));


    //map.addControl(new OpenLayers.Control.EditingToolbar(kadpodil));

    //map.addControl(new OpenLayers.Control.MousePosition());

    // style the sketch fancy
    var sketchSymbolizers = {
        "Point": {
            pointRadius: 4,
            graphicName: "square",
            fillColor: "white",
            fillOpacity: 1,
            strokeWidth: 1,
            strokeOpacity: 1,
            strokeColor: "#225086"
        },
        "Line": {
            strokeWidth: 3,
            strokeOpacity: 1,
            strokeColor: "#225086",
            strokeDashstyle: "dash"
        },
        "Polygon": {
            strokeWidth: 2,
            strokeOpacity: 1,
            strokeColor: "#225086",
            fillColor: "white",
            fillOpacity: 0.3
        }
    };
    var style = new OpenLayers.Style();
    style.addRules([
        new OpenLayers.Rule({
            symbolizer: sketchSymbolizers
        })
        ]);
    var styleMap = new OpenLayers.StyleMap({
        "default": style
    });

    // allow testing of specific renderers via "?renderer=Canvas", etc
    var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
    renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;

    measureControls = {
        line: new OpenLayers.Control.Measure(
            OpenLayers.Handler.Path, {
                persist: true,
                handlerOptions: {
                    layerOptions: {
                        renderers: renderer,
                        styleMap: styleMap
                    }
                }
            }
            ),
        polygon: new OpenLayers.Control.Measure(
            OpenLayers.Handler.Polygon, {
                persist: true,
                handlerOptions: {
                    layerOptions: {
                        renderers: renderer,
                        styleMap: styleMap
                    }
                }
            }
            )
    };

    var control;
    for(var key in measureControls) {
        control = measureControls[key];
        control.events.on({
            "measure": handleMeasurements,
            "measurepartial": handleMeasurements
        });
        map.addControl(control);
    }
}

function initPopupInfo()
{
    var popup = false;

    infoo = new OpenLayers.Control.WMSGetFeatureInfo({
        //layerUrls: serverMap+'/rastr/geoserver/dzk/wms',
        //layerUrls: serverMap+'/vector/geoserver/wms',

        //url: serverMap+'/vector/geoserver/wms',
        //url: serverMap+'/geoserver/wms',
        layerUrls: [serverMap+'/geowebcache/service/wms?tiled=true'],

        //layersUrls: ['dzk:kadastr'],
        //infoFormat: 'application/vnd.ogc.gml',
        infoFormat: 'text/html',
        //infoFormat: 'text/plain',
        title: 'Identify features by clicking',
        queryVisible: true,
        eventListeners: {
            /*beforegetfeatureinfo: function(){
        			//alert('sdf');
        		},*/
            getfeatureinfo: function(event) {

                //alert(event.text);

                $.ajax({
                    url : '/kadastrova-karta/get-feature-Info',
                    dataType: 'json',
                    async: false,
                    data : {
                        'html' : event.text
                    },
                    success :function(data){
                        if (popup){
                            popup.destroy();
                            popup=false;
                        }

                        var x = event.xy.x;
                        var y = event.xy.y;

                        $('#tooltip h3').html(data.title);
                        $('#tooltip .page[rel=1]').html(data.body);

                        $('#tooltip .switcher span').click(function(){
                            var id = $(this).attr('rel');
                            $('#tooltip .switcher span').removeClass('on');
                            $(this).addClass('on');

                            $('#tooltip .page').hide();
                            $('#tooltip .page[rel='+id+']').show();
                        });

                        tooltip.open('tooltip', x, y);
                    }
                });

            /*var info = explode('\n', event.text);

                var oInfo = {
                    koatuu : [],
                    zone : [],
                    quarter : [],
                    parcel : [],
                    natoobl : '',
                    patoobl : '',
                    natoray : '',
                    vpor : [],
                    vposs : []
                };

                $.each(info, function(index, row){
                    var items = explode('=', row);
                    if(items.length == 2)
                        switch(trim(new String(items[0]))){
                            case 'koatuu':
                                oInfo.koatuu.push(lpad(trim(new String(items[1])), 10, '0'));
                                break;
                            case 'zona':
                                oInfo.zone.push(lpad(trim(new String(items[1])), 2, '0'));
                                break;
                            case 'kvartal':
                            case 'kvart':
                                oInfo.quarter.push(lpad(trim(new String(items[1])), 3, '0'));
                                break;
                            case 'parcel':
                                oInfo.parcel.push(lpad(trim(new String(items[1])), 4, '0'));
                                break;
                            case 'natoobl':
                                oInfo.natoobl = items[1];
                                break;
                            case 'natoray':
                                oInfo.natoray = items[1];
                                break;
                            case 'patoobl':
                                oInfo.patoobl = items[1];
                                break;
                            case 'vpor':
                                oInfo.vpor.push(items[1]);
                                break;
                            case 'vposs':
                                oInfo.vposs.push(items[1]);
                                break;
                        }
                });

                var title = 'Інформацію не знайдено';
                var output = '';

                if(oInfo.parcel.length > 0){
                    title = '<h3>Ділянки(а)</h3>';
                    output = '<ul>';
                    $.each(oInfo.parcel, function(k, v){
                        output += '<li>';
                        output += '<span><strong>'+oInfo.koatuu[k]+':'+oInfo.zone[k]+':'+oInfo.quarter[k]+':'+oInfo.parcel[k]+'</strong></span>';
                        var p = getParcelInfo(oInfo.koatuu[k], oInfo.zone[k], oInfo.quarter[k], oInfo.parcel[k]);
                        if(p.length > 0){
                            if(p[0]['ownershipvalue']) output += '<div>'+p[0]['ownershipvalue']+'</div>';
                            if(p[0]['purpose']) output += '<div>'+p[0]['purpose']+'</div>';
                            //if(p[0]['ownershipcode']) output += '<div>'+p[0]['ownershipcode']+'</div>';
                            if(p[0]['area']) output += '<div>'+p[0]['area']+' '+p[0]['unit_area']+'</div>';
                        }
                        output += '</li>';
                    });
                    output += '</ul>';

                }
                if(oInfo.parcel.length == 0 && oInfo.quarter.length > 0) // Квартал

                {
                    $.ajax({
                        url : '/kadastrova-karta/get-Region-Info',
                        dataType: 'json',
                        async: false,
                        data : {
                            'koatuu' : oInfo.koatuu[0]
                        },
                        success :function(data){

                            title = '<h3>'+data['data']['region']+' область</h3>';
                            output = '<ul>';
                            output += '<li>';
                            output += '<div class="label">Район</div>';
                            output += '<div class="data">'+data['data']['district']+'</div>';
                            output += '</li>';
                            output += '<li>';
                            output += '<div class="label">Коатуу</div>';
                            output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
                            output += '</li>';
                            output += '<li>';
                            output += '<div class="label">Зона</div>';
                            output += '<div class="data">'+oInfo.zone[0]+'</div>';
                            output += '</li>';
                            output += '<li>';
                            output += '<div class="label">Квартал</div>';
                            output += '<div class="data">'+oInfo.quarter[0]+'</div>';
                            output += '</li>';
                            output += '</ul>';
                        }
                    });

                }else	if(oInfo.natoray != ''){ // Район
                    title = '<h3>'+oInfo.natoobl+' область</h3>';
                    output = '<ul>';
                    output += '<li>';
                    output += '<div class="label">Район</div>';
                    output += '<div class="data">'+oInfo.natoray+'</div>';
                    output += '</li>';
                    output += '<li>';
                    output += '<div class="label">Коатуу</div>';
                    output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
                    output += '</li>';
                    output += '</ul>';
                }else if(oInfo.patoobl != ''){	// Область
                    title = '<h3>'+oInfo.natoobl+' область</h3>';
                    output = '<ul>';
                    output += '<li>';
                    output += '<div class="label">Коатуу</div>';
                    output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
                    output += '</li>';
                    output += '</ul>';
                }

                if (popup){
                    popup.destroy();
                    popup=false;
                }

                var x = event.xy.x;
                var y = event.xy.y;

                $('#tooltip h3').html(title);
                $('#tooltip .page[rel=1]').html(output);

                $('#tooltip .switcher span').click(function(){
                    var id = $(this).attr('rel');
                    $('#tooltip .switcher span').removeClass('on');
                    $(this).addClass('on');

                    $('#tooltip .page').hide();
                    $('#tooltip .page[rel='+id+']').show();
                });

                tooltip.open('tooltip', x, y);*/

            /*popup = new OpenLayers.Popup.FramedCloud(
                            "chicken",
                            map.getLonLatFromPixel(event.xy),
                            null,
                            output,
                            null,
                            true
      		        );

    			    popup.closeOnMove = true;
    			    popup.autoSize = true;
    			    map.addPopup(popup);  */

            }
        }
    });

    map.addControl(infoo);
    infoo.activate();
}


function handleMeasurements(event) {
    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var element = document.getElementById('output');
    var out = "";
    if(order == 1) {
        out += "довжина: " + measure.toFixed(3) + " " + units;
    } else {
        out += "площа: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
    }

    $('#draw_feature_out').html(out);
//element.innerHTML = out;
}




// sets the HTML provided into the nodelist element
/* function setHTML(response){
                document.getElementById('nodelist').innerHTML = response.responseText;
            };*/

// shows/hide the control panel
function toggleControlPanel(event){
    var toolbar = document.getElementById("toolbar");
    if (toolbar.style.display == "none") {
        toolbar.style.display = "block";
    }
    else {
        toolbar.style.display = "none";
    }
    event.stopPropagation();
    map.updateSize()
}


// Transition effect, can be null or 'resize'
function setTransitionMode(transitionEffect){
    if (transitionEffect === 'resize') {
        tiled.transitionEffect = transitionEffect;
        untiled.transitionEffect = transitionEffect;
    }
    else {
        tiled.transitionEffect = null;
        untiled.transitionEffect = null;
    }
}

function setPalette(mode){
    if (mode == '') {
        tiled.mergeNewParams({
            palette: null
        });
        untiled.mergeNewParams({
            palette: null
        });
    }
    else {
        tiled.mergeNewParams({
            palette: mode
        });
        untiled.mergeNewParams({
            palette: mode
        });
    }
}

function setWidth(size){
    var mapDiv = document.getElementById('map');
    var wrapper = document.getElementById('wrapper');

    if (size == "auto") {
        // reset back to the default value
        mapDiv.style.width = null;
        wrapper.style.width = null;
    }
    else {
        mapDiv.style.width = size + "px";
        wrapper.style.width = size + "px";
    }
    // notify OL that we changed the size of the map div
    map.updateSize();
}

function setHeight(size){
    var mapDiv = document.getElementById('map');

    if (size == "auto") {
        // reset back to the default value
        mapDiv.style.height = null;
    }
    else {
        mapDiv.style.height = size + "px";
    }
    // notify OL that we changed the size of the map div
    map.updateSize();
}

function mergeNewParams(params){
    tiled.mergeNewParams(params);
    untiled.mergeNewParams(params);
}

function osm_getTileURL(bounds) {
    var res = this.map.getResolution();
    var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
    var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
    var z = this.map.getZoom();
    var limit = Math.pow(2, z);

    if (y < 0 || y >= limit) {
        return "http://www.maptiler.org/img/none.png";
    } else {
        x = ((x % limit) + limit) % limit;
        return this.url + z + "/" + x + "/" + y + "." + this.type;
    }
}

function overlay_getTileURL(bounds) {
    var res = this.map.getResolution();
    var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
    var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
    var z = this.map.getZoom();
    if (this.map.baseLayer.name == 'Virtual Earth Roads' || this.map.baseLayer.name == 'Virtual Earth Aerial' || this.map.baseLayer.name == 'Virtual Earth Hybrid') {
        z = z + 1;
    }
    if (mapBounds.intersectsBounds( bounds ) && z >= mapMinZoom && z <= mapMaxZoom ) {
        //console.log( this.url + z + "/" + x + "/" + y + "." + this.type);
        //alert (map.layers[4].visibility);


        if (map.layers[6].visibility == true) {
            return "http://212.26.144.107:8092/ukraine_jpg/" + z + "/" + x + "/" + y + "." + this.type
        };
        if (map.layers[7].visibility = true) {
            return "http://212.26.144.107:8092/333/" + z + "/" + x + "/" + y + "." + this.type
        };


    } else {
        //alert;
        return "http://www.maptiler.org/img/none.png";
    }
}

function resize() {
    var map = document.getElementById("map");
    var leftSideWidth = 0;

    map.style.height = (getWindowHeight()-72) + "px";

    // if($('.sidebar').is(':visible')) leftSideWidth = 280;

    map.style.width = (getWindowWidth()-2-leftSideWidth) + "px";
    if (map.updateSize) {
        map.updateSize();
    };
}

function getParcelInfo(koatuu, zone, quartal, parcel)
{
    var ret;
    $.ajax({
        url : '/kadastrova-karta/get-parcel-Info',
        dataType: 'json',
        async: false,
        data : {
            'koatuu' : koatuu,
            'zone' : zone,
            'quartal' : quartal,
            'parcel' : parcel
        },
        success :function(data){
            ret =  data;
        }
    });
    return ret['data'];
}

function searchCadnum(cadnum){

    var koatuu_area = parseFloat(rpad(cadnum.substring(0, 2), 10, '0'));
    var koatuu_district = parseFloat(rpad(cadnum.substring(0, 5), 10, '0'));


    Proj4js.defs["EPSG:4284"] = '+proj=longlat+ellps=kras+towgs84=23.92,-141.27,-80.9,-0,0.35,0.82,-0.12+no_defs';
    Proj4js.defs["EPSG:4326"] = '+proj=longlat+ellps=WGS84+datum=WGS84+no_defs+towgs84=0,0,0';
    Proj4js.defs["EPSG:900913"] = '+proj=merc+a=6378137+b=6378137+lat_ts=0.0+lon_0=0.0+x_0=0.0+y_0=0+k=1.0+units=m+nadgrids=@null+wktext+over+no_defs';

    var src = new Proj4js.Proj("EPSG:4284");
    var dst = new Proj4js.Proj("EPSG:900913");

    $('#id_region option').removeAttr('selected');
    $('#id_region option[rel='+koatuu_area+']').attr('selected', true);

    $('#id_district option').removeAttr('selected');
    $('#id_city option').removeAttr('selected');

    change_region(koatuu_district);


    $.getJSON('/kadastrova-karta/find-Parcel', {
        'cadnum' : cadnum
    }, function(data){

        if(data['status'] && data['data'][0]['st_xmin'] != null){
            var x1 = data['data'][0]['st_xmin'];
            var y1 = data['data'][0]['st_ymin'];
            var x2 = data['data'][0]['st_xmax'];
            var y2 = data['data'][0]['st_ymax'];

            var point1 = new Proj4js.Point(x1,y1);
            var point2 = new Proj4js.Point(x2,y2);

            Proj4js.transform(src, dst, point1);
            Proj4js.transform(src, dst, point2);

            var new_response =  point1.x + "," + point1.y + "," + point2.x + "," + point2.y;
            var new_bounds_res = new OpenLayers.Bounds.fromString(new_response);

            //var mapBounds = new OpenLayers.Bounds(data['data'][0]['st_xmin'], data['data'][0]['st_ymin'], data['data'][0]['st_xmax'], data['data'][0]['st_ymax']);
            //map.zoomToExtent( mapBounds.transform(map.displayProjection, map.projection ));
            map.zoomToExtent(new_bounds_res);

            var x = new_bounds_res.centerLonLat.lat;
            var y = new_bounds_res.centerLonLat.lon;

            //alert(y+':'+x);

            map.setCenter(new OpenLayers.LonLat(y,x),21);
            var cad_arr = explode(':', cadnum);
            var p = getParcelInfo(cad_arr[0], cad_arr[1], cad_arr[2], cad_arr[3]);

            title = '<h3>Ділянка</h3>';
            output = '<ul>';

            output += '<li>';
            output += '<span><strong>'+cadnum+'</strong></span>';
            if(p.length > 0){
                if(p[0]['ownershipvalue']) output += '<div>'+p[0]['ownershipvalue']+'</div>';
                if(p[0]['purpose']) output += '<div>'+p[0]['purpose']+'</div>';
                //if(p[0]['ownershipcode']) output += '<div>'+p[0]['ownershipcode']+'</div>';

                if(p[0]['area']) output += '<div>'+p[0]['area']+' '+p[0]['unit_area']+'</div>';
            }
            output += '</li>';
            output += '</ul>';

            $('#tooltip h3').html(title);
            $('#tooltip .page[rel=1]').html(output);

            $('#tooltip .switcher span').click(function(){
                var id = $(this).attr('rel');
                $('#tooltip .switcher span').removeClass('on');
                $(this).addClass('on');

                $('#tooltip .page').hide();
                $('#tooltip .page[rel='+id+']').show();
            });

            tooltip.open('tooltip', getWindowWidth()/2, getWindowHeight()/2 - 50);

        }else{
            if(data['status']){
                $('#popup_find_msg strong.cadnum').html(cadnum);
                popup.open('popup_find_msg');
            } else{
                alert(data['msg']);
            }
        }
    });

}

function searchGoggle(address){
    var geoCoder = new google.maps.Geocoder(address);
    var request = {
        address:address
    };
    //var map = document.getElementById("map");

    geoCoder.geocode(request, function(result, status){
        if(!isset(result[0])){
            alert('За данним запитом відомості відсутні.');
            return false;
        }
        var proj = new OpenLayers.Projection("EPSG:4326");
        var point = new OpenLayers.LonLat(result[0].geometry.location.lng(), result[0].geometry.location.lat());
        var LonLat = point.transform(proj, map.getProjectionObject())


        var size = new OpenLayers.Size(21,25);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);
        var marker = new OpenLayers.Marker(LonLat, icon);
        marker.events.register('mousedown', marker, function(evt) {
            alert(address);
            OpenLayers.Event.stop(evt);
        });
        markers.addMarker(marker);
        map.setCenter(LonLat, 16);
    })
}

function is_cadnum(s){
    var s_arr = explode(':', s);
    if(s_arr.length != 4) return false;

    if(parseFloat(s_arr[0]) > 0 && parseFloat(s_arr[1]) > 0 && parseFloat(s_arr[2]) > 0 && parseFloat(s_arr[3]) > 0)
        return true;

    return false;
}

onresize=function(){
    resize();
};
